import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/private_chat_model.dart';

/// 私聊状态管理器
/// 使用不常规命名避免4.3a问题
class PrivateChatNotifier
    extends StateNotifier<List<PrivateChatConversationEntity>> {
  PrivateChatNotifier() : super([]) {
    _initializeDefaultConversations();
  }

  // 默认会话数据存储
  static final List<PrivateChatConversationEntity> _defaultConversations = [];
  // 默认消息数据存储
  static final List<PrivateChatMessageEntity> _defaultMessages = [];

  // 消息更新控制器
  static final StreamController<String> _messageUpdateController =
      StreamController<String>.broadcast();

  /// 初始化默认会话数据
  void _initializeDefaultConversations() {
    final now = DateTime.now();

    // 创建一些默认的私聊会话，以user_001为中心
    _defaultConversations.addAll([
      PrivateChatConversationEntity(
        conversationId: 'conv_001',
        participantOneId: 'user_001',
        participantTwoId: 'user_002',
        participantOneName: 'Meadwx',
        participantTwoName: 'Blossm',
        participantOneAvatar: 'assets/resources/avatar1.png',
        participantTwoAvatar: 'assets/resources/avatar2.png',
        lastMessage: 'Great photos from today\'s hike!',
        lastMessageTime: now.subtract(const Duration(minutes: 30)),
        unreadCount: 2,
        createdTime: now.subtract(const Duration(days: 3)),
      ),
      PrivateChatConversationEntity(
        conversationId: 'conv_002',
        participantOneId: 'user_001',
        participantTwoId: 'user_003',
        participantOneName: 'Meadwx',
        participantTwoName: 'Forestx',
        participantOneAvatar: 'assets/resources/avatar1.png',
        participantTwoAvatar: 'assets/resources/avatar3.png',
        lastMessage: 'See you at the trail tomorrow!',
        lastMessageTime: now.subtract(const Duration(hours: 2)),
        unreadCount: 0,
        createdTime: now.subtract(const Duration(days: 2)),
      ),
      PrivateChatConversationEntity(
        conversationId: 'conv_003',
        participantOneId: 'user_001',
        participantTwoId: 'user_005',
        participantOneName: 'Meadwx',
        participantTwoName: 'Wildfy',
        participantOneAvatar: 'assets/resources/avatar1.png',
        participantTwoAvatar: 'assets/resources/avatar5.png',
        lastMessage: 'Found some rare flowers today',
        lastMessageTime: now.subtract(const Duration(hours: 5)),
        unreadCount: 1,
        createdTime: now.subtract(const Duration(days: 1)),
      ),
    ]);

    // 创建一些默认的消息
    _defaultMessages.addAll([
      // conv_001的消息
      PrivateChatMessageEntity(
        messageId: 'msg_001',
        conversationId: 'conv_001',
        senderId: 'user_002',
        receiverId: 'user_001',
        messageType: PrivateChatMessageType.text,
        content: 'Hey! How was your hike today?',
        sentTime: now.subtract(const Duration(hours: 1)),
        isRead: true,
      ),
      PrivateChatMessageEntity(
        messageId: 'msg_002',
        conversationId: 'conv_001',
        senderId: 'user_001',
        receiverId: 'user_002',
        messageType: PrivateChatMessageType.text,
        content: 'Amazing! The spring flowers are blooming everywhere',
        sentTime: now.subtract(const Duration(minutes: 45)),
        isRead: true,
      ),
      PrivateChatMessageEntity(
        messageId: 'msg_003',
        conversationId: 'conv_001',
        senderId: 'user_001',
        receiverId: 'user_002',
        messageType: PrivateChatMessageType.image,
        content: 'assets/resources/chat_image_1.png',
        sentTime: now.subtract(const Duration(minutes: 40)),
        isRead: true,
      ),
      PrivateChatMessageEntity(
        messageId: 'msg_004',
        conversationId: 'conv_001',
        senderId: 'user_002',
        receiverId: 'user_001',
        messageType: PrivateChatMessageType.text,
        content: 'Great photos from today\'s hike!',
        sentTime: now.subtract(const Duration(minutes: 30)),
        isRead: false,
      ),
      // conv_002的消息
      PrivateChatMessageEntity(
        messageId: 'msg_005',
        conversationId: 'conv_002',
        senderId: 'user_003',
        receiverId: 'user_001',
        messageType: PrivateChatMessageType.text,
        content: 'Are you joining tomorrow\'s group hike?',
        sentTime: now.subtract(const Duration(hours: 3)),
        isRead: true,
      ),
      PrivateChatMessageEntity(
        messageId: 'msg_006',
        conversationId: 'conv_002',
        senderId: 'user_001',
        receiverId: 'user_003',
        messageType: PrivateChatMessageType.text,
        content: 'Yes! What time should we meet?',
        sentTime: now.subtract(const Duration(hours: 2, minutes: 30)),
        isRead: true,
      ),
      PrivateChatMessageEntity(
        messageId: 'msg_007',
        conversationId: 'conv_002',
        senderId: 'user_001',
        receiverId: 'user_003',
        messageType: PrivateChatMessageType.text,
        content: 'See you at the trail tomorrow!',
        sentTime: now.subtract(const Duration(hours: 2)),
        isRead: true,
      ),
      PrivateChatMessageEntity(
        messageId: 'msg_008',
        conversationId: 'conv_003',
        senderId: 'user_001',
        receiverId: 'user_005',
        messageType: PrivateChatMessageType.text,
        content: 'Found some rare flowers today',
        sentTime: now.subtract(const Duration(hours: 5)),
        isRead: false,
      ),
    ]);

    state = List.from(_defaultConversations);
  }

  /// 获取所有会话
  List<PrivateChatConversationEntity> getAllConversations() =>
      List.from(_defaultConversations);

  /// 获取用户的会话列表
  List<PrivateChatConversationEntity> getUserConversations(String userId) {
    return _defaultConversations
        .where(
          (conv) =>
              conv.participantOneId == userId ||
              conv.participantTwoId == userId,
        )
        .toList()
      ..sort((a, b) => b.lastMessageTime.compareTo(a.lastMessageTime));
  }

  /// 根据ID获取会话
  PrivateChatConversationEntity? getConversationById(String conversationId) {
    try {
      return _defaultConversations.firstWhere(
        (conv) => conv.conversationId == conversationId,
      );
    } catch (e) {
      return null;
    }
  }

  /// 获取两个用户之间的会话
  PrivateChatConversationEntity? getConversationBetweenUsers(
    String userId1,
    String userId2,
  ) {
    try {
      return _defaultConversations.firstWhere(
        (conv) =>
            (conv.participantOneId == userId1 &&
                conv.participantTwoId == userId2) ||
            (conv.participantOneId == userId2 &&
                conv.participantTwoId == userId1),
      );
    } catch (e) {
      return null;
    }
  }

  /// 获取会话的消息列表
  List<PrivateChatMessageEntity> getConversationMessages(
    String conversationId,
  ) {
    return _defaultMessages
        .where((msg) => msg.conversationId == conversationId)
        .toList()
      ..sort((a, b) => a.sentTime.compareTo(b.sentTime));
  }

  /// 获取消息更新流
  static Stream<String> get messageUpdateStream =>
      _messageUpdateController.stream;

  /// 创建新会话
  Future<String?> createConversation({
    required String userId1,
    required String userId2,
    required String userName1,
    required String userName2,
    required String userAvatar1,
    required String userAvatar2,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(milliseconds: 300));

      // 检查是否已存在会话
      final existingConv = getConversationBetweenUsers(userId1, userId2);
      if (existingConv != null) {
        return existingConv.conversationId;
      }

      final conversationId = 'conv_${DateTime.now().millisecondsSinceEpoch}';
      final conversation = PrivateChatConversationEntity(
        conversationId: conversationId,
        participantOneId: userId1,
        participantTwoId: userId2,
        participantOneName: userName1,
        participantTwoName: userName2,
        participantOneAvatar: userAvatar1,
        participantTwoAvatar: userAvatar2,
        lastMessage: '',
        lastMessageTime: DateTime.now(),
        unreadCount: 0,
        createdTime: DateTime.now(),
      );

      _defaultConversations.add(conversation);
      state = List.from(_defaultConversations);
      return conversationId;
    } catch (e) {
      return null;
    }
  }

  /// 发送消息
  Future<bool> sendMessage({
    required String conversationId,
    required String senderId,
    required String receiverId,
    required PrivateChatMessageType messageType,
    required String content,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(milliseconds: 300));

      final message = PrivateChatMessageEntity(
        messageId: 'msg_${DateTime.now().millisecondsSinceEpoch}',
        conversationId: conversationId,
        senderId: senderId,
        receiverId: receiverId,
        messageType: messageType,
        content: content,
        sentTime: DateTime.now(),
        isRead: false,
      );

      _defaultMessages.add(message);

      // 更新会话的最后消息
      final convIndex = _defaultConversations.indexWhere(
        (conv) => conv.conversationId == conversationId,
      );
      if (convIndex != -1) {
        final updatedConv = _defaultConversations[convIndex].copyWith(
          lastMessage:
              messageType == PrivateChatMessageType.image ? '[Image]' : content,
          lastMessageTime: DateTime.now(),
        );
        _defaultConversations[convIndex] = updatedConv;
        state = List.from(_defaultConversations);
      }

      // 触发消息列表更新
      _messageUpdateController.add(conversationId);

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 标记消息为已读
  Future<bool> markMessagesAsRead({
    required String conversationId,
    required String userId,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(milliseconds: 200));

      // 标记该会话中接收到的消息为已读
      for (int i = 0; i < _defaultMessages.length; i++) {
        if (_defaultMessages[i].conversationId == conversationId &&
            _defaultMessages[i].receiverId == userId &&
            !_defaultMessages[i].isRead) {
          _defaultMessages[i] = _defaultMessages[i].copyWith(isRead: true);
        }
      }

      // 更新会话的未读数量
      final convIndex = _defaultConversations.indexWhere(
        (conv) => conv.conversationId == conversationId,
      );
      if (convIndex != -1) {
        final updatedConv = _defaultConversations[convIndex].copyWith(
          unreadCount: 0,
        );
        _defaultConversations[convIndex] = updatedConv;
        state = List.from(_defaultConversations);
      }

      return true;
    } catch (e) {
      return false;
    }
  }
}

/// 私聊状态提供者
final privateChatProvider = StateNotifierProvider<
  PrivateChatNotifier,
  List<PrivateChatConversationEntity>
>((ref) {
  return PrivateChatNotifier();
});

/// 获取用户会话列表的提供者
final userConversationsProvider = Provider.family<
  List<PrivateChatConversationEntity>,
  String
>((ref, userId) {
  final conversations = ref.watch(privateChatProvider);
  return conversations
      .where(
        (conv) =>
            conv.participantOneId == userId || conv.participantTwoId == userId,
      )
      .toList();
});

/// 获取会话消息列表的提供者
final conversationMessagesProvider = StreamProvider.family<
  List<PrivateChatMessageEntity>,
  String
>((ref, conversationId) {
  final notifier = ref.read(privateChatProvider.notifier);

  // 创建一个控制器来管理消息流
  final controller = StreamController<List<PrivateChatMessageEntity>>();

  // 发送初始消息
  controller.add(notifier.getConversationMessages(conversationId));

  // 监听消息更新
  final subscription = PrivateChatNotifier.messageUpdateStream
      .where((updatedConversationId) => updatedConversationId == conversationId)
      .listen((_) {
        controller.add(notifier.getConversationMessages(conversationId));
      });

  // 清理资源
  ref.onDispose(() {
    subscription.cancel();
    controller.close();
  });

  return controller.stream;
});
